﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

namespace Gueei.Gallery.Core.DisplayProfiles
{
	public class ForceSizedThumbDisplayProfile : DisplayProfile
	{
		public override byte[] ConvertImage(byte[] original, string mime)
		{
			System.Drawing.Image imgToResize = System.Drawing.Image.FromStream(
				new MemoryStream(original)
				);

			int sourceWidth = imgToResize.Width;
			int sourceHeight = imgToResize.Height;

			float nPercent = 0;
			float nPercentW = 0;
			float nPercentH = 0;

			nPercentW = ((float)MaxWidth / (float)sourceWidth);
			nPercentH = ((float)MaxHeight / (float)sourceHeight);

			nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;

			var destWidth = (int)(sourceWidth * nPercent);
			var destHeight = (int)(sourceHeight * nPercent);

			var b = new Bitmap(MaxWidth, MaxHeight);
			Graphics g = Graphics.FromImage((System.Drawing.Image)b);
			g.InterpolationMode = InterpolationMode.HighQualityBicubic;

			int x = 0;
			int y = 0;
			x = destWidth < MaxWidth ? (MaxWidth - destWidth)/2 : 0;
			y = destHeight < MaxHeight ? (MaxHeight - destHeight)/2 : 0;

			g.Clear(Color.White);
			g.DrawImage(imgToResize,x, y, destWidth, destHeight);
			g.Dispose();

			var ms = new MemoryStream();
			b.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
			return ms.ToArray();
		}
	}
}
